package com.kunchi.platform.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.kunchi.platform.service.LoginService;
import com.kunchi.platform.utils.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.MessageFormat;

/**
 * Created by denniszhou on 2017/6/19.
 */
@Service("loginService")
@PropertySource("classpath:config.properties")
public class LoginServiceImpl implements LoginService {

    private static Logger logger = LoggerFactory.getLogger(LoginServiceImpl.class);

    @Autowired
    Environment env;

    @Override
    public String login() throws IOException {
        String url = env.getRequiredProperty("BASE_URL") + "/user/login";
        JSONObject account = new JSONObject();
        account.put("name", env.getRequiredProperty("LOGIN_NAME"));
        account.put("password", env.getRequiredProperty("LOGIN_PASSWORD"));
        account.put("hash", env.getRequiredProperty("LOGIN_HASH"));
        String response = HttpUtils.getHttpPostResponse(MessageFormat.format(
                url, env.getRequiredProperty("LOGIN_NAME"),
                env.getRequiredProperty("LOGIN_PASSWORD"),
                env.getRequiredProperty("LOGIN_HASH")), account);
        return JSONObject.parseObject(response).getString("data");
    }

    @Override
    public String rentLogin() throws IOException {
        String url = env.getRequiredProperty("BASE_URL") + "/user/getToken";
        JSONObject account = new JSONObject();
        account.put("tenantEname", env.getRequiredProperty("RENT_LOGIN_TENANTENAME"));
        account.put("name", env.getRequiredProperty("RENT_LOGIN_NAME"));
        account.put("password", env.getRequiredProperty("RENT_LOGIN_PASSWORD"));
        account.put("hash", env.getRequiredProperty("RENT_LOGIN_HASH"));
        String response = HttpUtils.getHttpPostResponse(MessageFormat.format(
                url, env.getRequiredProperty("RENT_LOGIN_TENANTENAME"),
                env.getRequiredProperty("RENT_LOGIN_NAME"),
                env.getRequiredProperty("RENT_LOGIN_PASSWORD"),
                env.getRequiredProperty("RENT_LOGIN_HASH")), account);
        return JSONObject.parseObject(response).getString("data");
    }
}
